package com.xinyue.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.xinyue.user.pojo.User;
import com.xinyue.user.service.UserService;
import com.xinyue.user.utils.CodesUtils;
import com.xinyue.user.utils.FileUtils;
import com.xinyue.user.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {
	@Autowired
    private UserService userService;
    /**
     *   用户名/手机号 + 密码登录
     * @param username 用户名
     * @param password 密码
     * @param phone    手机号
     * @return  JsonResult  state 200 正常 ，其余异常       data  用户对象   message  提示信息
     */
    @RequestMapping("/login")
    public JsonResult  login(String username,String password,String phone,HttpSession session){
        User user = null;
        System.out.println(username+"--"+password+"--"+phone);
        try {
            if (username!=null && !username.equals("")){
                user = userService.selectToLoginByUsername(username,password);
             }else if(phone != null && !phone.equals("")){
                 user = userService.selectToLoginByPhone(phone, password);
            }else{
                System.out.println("手机号验证码登录！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(user!=null){
            session.setAttribute("user",user);
            System.out.println(user);
            return new JsonResult(200,user,"登录成功！");
        }
        else return new JsonResult(201, null,"账号或密码错误！");
    }

    /**
     *
     * @param phone  手机号
     * @param session  储存验证码信息
     * @return JsonResult  state 200 正常 ，其余异常   data  验证码信息   message  提示信息
     */
    @RequestMapping("/sendSms")
    public JsonResult SendSms(String phone,HttpSession session){
        int code= CodesUtils.getCodes();
        System.out.println(phone+":"+code);
        try {
            //if(AliyunUtils.sendSMS(phone,code)){
            if(true){
                System.out.println("发送成功！");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("phone",phone);
                jsonObject.put("code",code+"");
                jsonObject.put("createTime",System.currentTimeMillis());
                System.out.println(jsonObject);
                session.setAttribute("phone_code",jsonObject);
                return new JsonResult(200,code,"发送成功！");
            }else{
                System.out.println("发送失败！");
                return new JsonResult(201,null,"发送失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送失败！");
            return new JsonResult(201,null,"发送失败！");
        }

    }
    //手机号验证码登录
    @RequestMapping("/loginByPhone")
    public JsonResult loginByPhone(String verificationCode,HttpSession session){
        //String u=(String)session.getAttribute("u");
        System.out.println("--------"+verificationCode);
        JSONObject phone_code = (JSONObject)session.getAttribute("phone_code");
        if (phone_code == null){
            return new JsonResult(201,null,"获取手机号验证码后在登陆！");
        }
        if(!phone_code.getString("code").equals(verificationCode+"")){
            return new JsonResult(201,null,"验证码错误！");
        }
        if((System.currentTimeMillis() - phone_code.getLong("createTime")) > 1000 * 60 * 5){
            return new JsonResult(201,null,"验证码过期！");
        }
        String phone = phone_code.getString("phone");

        try {
            User userInfo=userService.selectByPhone(phone);
            //验证是否为新注册用户
            if (userInfo == null){
                User user = new User();
                user.setPhone(phone);
                userService.insert(user);
                System.out.println(user.getId());
                session.setAttribute("user",user);
                return new JsonResult(200,user,"新注册用户！");
            }else{
                return new JsonResult(200,userInfo,"已注册用户！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(201,null,"登录异常！");
        }
} 
    //手机号验证码重置密码
    @RequestMapping("/resetPwd")
    public JsonResult resetPwd(String phone,String verificationCode,String password,HttpSession session){
        System.out.println(phone+"--------"+verificationCode+"---"+password);
        JSONObject phone_code = (JSONObject)session.getAttribute("phone_code");
        
        if (phone_code == null){
            return new JsonResult(201,null,"获取手机号验证码后在登陆！");
        }
      
        if(!phone_code.getString("phone").equals(phone)){
            return new JsonResult(201,null,"手机号错误！");
        }
        if(!phone_code.getString("code").equals(verificationCode+"")){
            return new JsonResult(201,null,"验证码错误！");
        }
        if((System.currentTimeMillis() - phone_code.getLong("createTime")) > 1000 * 60 * 5){
            return new JsonResult(201,null,"验证码过期！");
        }
        String phone1 = phone_code.getString("phone");
        try {
            User userInfo=userService.selectByPhone(phone1); 
            User user = new User();
            user.setPhone(phone1);
            user.setPassword(password);
            //验证是否为新注册用户
            if (userInfo == null){
                userService.insert(user);
                System.out.println(user.getId());
                session.setAttribute("user",user);
                return new JsonResult(200,user,"新用户，直接注册");
            }else{
            	user.setId(userInfo.getId());
            	userService.updateByPrimaryKey(user);
                return new JsonResult(200,user,"修改成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(201,null,"修改失败！");
        }
}
    @RequestMapping("/register")
    public JsonResult register(User user){
    	try {
			userService.insert(user);
			System.out.println(user);
			return new JsonResult(200,user,"正常！");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonResult(201,null,"设置异常！");
		}
        
    }

    //设置个人信息，头像，昵称，性别,地址，生日，兴趣
    @RequestMapping("/updateMess")
    public JsonResult updateMess(User user ,@RequestParam(name = "picture",required = false) MultipartFile file,HttpSession session){
    	System.out.println("用户信息："+user);
        User userInfo=(User)session.getAttribute("user");
        System.out.println(userInfo);
        if(userInfo==null){
        	return new JsonResult(201,null,"设置异常！");
        }
        user.setId(userInfo.getId());
        if(file!=null){
        	String avatar = FileUtils.getRandomFileName(file);
        	user.setAvatar("img/"+avatar);
        	try {
				file.transferTo(new File("C:/upload/img/"+FileUtils.getRandomFileName(file)));
			} catch (Exception e) {
				e.printStackTrace();
				return new JsonResult(201,null,"设置异常！");
			}
        }
        try {
            int i = userService.updateByPrimaryKey(user);
            return new JsonResult(200,null,"设置正常！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(201,null,"设置异常！");
    }
    //设置个人信息，头像，昵称，性别,地址，生日，兴趣
    @RequestMapping("/user/updateUser")
    public JsonResult updateUser(User user){
    	System.out.println("用户信息："+user);
        try {
            int i = userService.updateByPrimaryKey(user);
            return new JsonResult(200,null,"设置正常！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(201,null,"设置异常！");
    }
    //8082/user/queryAll
    @RequestMapping("/user/queryAll")
    public List<User> queryAll(){
        //允许所有人访问
        List<User> users = null;
        try {
            users = userService.selectAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }
  //8082/user/queryAll
    @RequestMapping("/user/queryById")
    public JsonResult queryById(Integer id,HttpSession session){
    	//System.out.println(Integer.valueOf(id));
    	User userInfo =(User)session.getAttribute("user");
    	if(userInfo!=null &&userInfo.getId()!=null){
    		 id=userInfo.getId();
    	}
        User user = null;
        try {
            user = userService.selectByPrimaryKey(id);
            System.out.println(user);
            if(user != null) return new JsonResult(200,user,"返回数据成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(201,null,"返回数据失败！");
    }
   @ResponseBody
   @RequestMapping("/upload")
   public String upload(User user, @RequestParam("picture") MultipartFile file){
       try {
           System.out.println(user);

           file.transferTo(new File("C:/upload/img/"+file.getOriginalFilename()));
       } catch (Exception e) {
           e.printStackTrace();
           return "error";
       }
       return "success";
   }

}
